/**
 * @author LoneWolf
 * axios 二次封装
 */

import axios, { AxiosRequestConfig } from 'axios'
import config from '@/config'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import userStore from '@/store/user'
import router from '@/router'
//配置进度条参数
NProgress.configure({
    showSpinner: true,
    minimum: 0.2,
    easing: 'swing',
    speed: 1000,
})

//防止多次请求进度条重复加载
let loadingNum = 0
function startLoading() {
    if (loadingNum == 0) {
        NProgress.start()
    }
    loadingNum++
}
function endLoading() {
    loadingNum--
    if (loadingNum <= 0) {
        NProgress.done()
    }
}

const instance = axios.create({
    timeout: 1000 * 7,
})

// 请求拦截
instance.interceptors.request.use((req) => {
    startLoading()
    const headers = req.headers
    if (headers)
        if (!userStore.$state.token) {
            router.push('/login')
        } else {
            headers.Authorization = `Bearer ${userStore.$state.token}`
        }
    return req
})

// 响应拦截
instance.interceptors.response.use(
    (res) => {
        endLoading()
        const {
            data: { code, msg },
        } = res
        if (code === 200) return res.data
        else if (msg) {
            ElMessage.closeAll()
            ElMessage.error(msg)
        } else {
            ElMessage.error('网络请求失败，请稍后重试')
        }
    },
    ({ response: res }) => {
        ElMessage.error(`接口请求失败：${res.message}`)
    }
)

export interface IOptions extends AxiosRequestConfig {
    method?: 'get' | 'post' | 'put' | 'delete' | 'patch'
    params?: object
}

const ajax = (url: string, options: IOptions = {}, mock: boolean = false) => {
    let baseURL = config.baseApi
    if (!options.method) options.method = 'get'

    if (options.method === 'get') {
        options.params = options.data
    }
    // 如果为生产环境 则强制使用 baseApi ，防止漏删mock
    if (config.env === 'prod') {
        baseURL = config.baseApi
    } else if (config.mock) {
        baseURL = config.mockApi
    } else if (mock) {
        baseURL = config.mockApi
    }
    url = baseURL + url
    return instance({
        url,
        ...options,
    })
}

export default ajax
